(function ($) {
    var zhpLangs = {
        'zh_cn': {
            'Select pictures': '点击选择图片',
            'Upload': '开始上传',
            'Add': '继续添加',
            'Request error!': '请求出错！',
            'Continue': '继续操作',
            'Go Back': '返回',
            'Delete': '删除',
        }
    };
    function zhpLang(str) {
        var lang = $.zui.clientLang();
        if (!zhpLangs[lang])
            return str;
        if (!zhpLangs[lang][str])
            return str;
        return zhpLangs[lang][str];
    }
    //针对已经在HTML中手动写入的单选框进行一下处理
    $('.radio label').each(function () {
        var e = $(this);
        e.click(function () {
            e.closest('.radio').find("label").removeClass("active");
            e.closest('.radio').find('span').removeClass('icon-check');
            //e.closest('.radio').find('input').removeAttr('checked');      //不能直接用removeAttr，这样会删除掉整个元素
            e.find('input').first().attr('checked', true);
            e.find('span').addClass('icon-check');
            e.addClass("active");
        });
    });
    //针对已经在HTML中手动写入的复选框进行一下处理。
    $('.checkbox label').each(function () {
        var e = $(this);
        e.click(function () {
            if (e.find('input').is(':checked')) {
                e.addClass("active");
            } else {
                e.removeClass("active");
            }
        });
    });

    //表单处理，要实现的目标是尽可能简单的写入HTML而使其尽可能美观的呈现出来
    $.fn.zhpForm = function (options) {
        var defaults = {
            postFun: {},
            returnFun: {},
            errorFun: {}
        };
        options = $.extend(defaults, options);
        this.each(function () {
            //表单提交
            var form = this;
            Do.ready('form', 'tips', function () {
                $ajax = $(form).data('toggle');
                if ($ajax == 'ajaxform')
                    $ajax = true;
                else
                    $ajax = false;
                var onsubmit = $(form).attr('onsubmit');
                $(form).removeAttr('onsubmit');
                var returnFun = $(form).attr('data-return');
                if($.isExitsFunction(returnFun)){
                    options.returnFun = returnFun;
                }
                $(form).Validform({
                    ajaxPost: $ajax,
                    ajax: $ajax,
                    postonce: true,
                    beforeSubmit: function () {
                        toastr.info('正在提交数据，请等待......');
                        if (onsubmit) {
                            onsubmit = onsubmit.replace('return ', '');
                            return eval(onsubmit);
                        }
                        return true;
                    },
                    tiptype: function (msg, o, cssctl) {
                        if (!o.obj.is("form")) {
                            if (o.type == 2) {
                                //通过
                                o.obj.parents('.form-group').removeClass('has-error');
                            }
                            if (o.type == 3) {
                                //未通过
                                toastr.error(msg);
                                o.obj.parents('.form-group').addClass('has-error');
                            }
                            //因为select等被转换过了，所以没法直接获取焦点，就只好用屏幕滚动来解决了。
                            if(o.obj.is(':hidden')){
                                pos = $(o.obj).parent().offset();
                            } else {
                                pos = $(o.obj).offset();
                            }
                            $('html,body').animate({scrollTop:pos.top}, 1);
                        }
                    },
                    callback: function (data) {
                        if(!$ajax) {
                            return true;
                        }
                        if (data.readyState == 4 && !data.msg && data.status == 200) {
                            toastr.error(zhpLang('Request error!'));
                            return;
                        }
                        if (data.readyState == 4 && !data.msg) {
                            toastr.error(zhpLang('Request error!'));
                            return;
                        }
                        toastr.clear();
                        if (data.code == 1) {
                            //成功返回
                            if ($.isExitsFunction(options.returnFun)) {
                                eval(options.returnFun+'(data)')
                            }
                        } else {
                            if ($.isExitsFunction(options.errorFun)) {
                                options.errorFun(data);
                            }
                        }
                        var type = data.code == 1 ? 'info' : 'error';
                        var alertTimeout = data.code==1?1500:3000;
                        if (data.url == null || data.url == '') {
                            //不带连接
                            if(data.msg) {
                                $.zui.alertmsg(type, data.msg);
                            }
                        } else {
                            var url = data.url;
                            //带连接
                            if ($ajax) {
                                $.zui.alertmsg(type, data.msg?data.msg:"确认一下吧", {
                                    displayMode: 'slide',
                                    displayPosition: 'topcenter',
                                    alertTimeout: alertTimeout,
                                    closeCall: function () {
                                        window.location = url;
                                    }
                                });
                            }
                            else {
                                window.location = url;
                            }
                        }
                    }
                });
            });
        });
    };

    //列表框处理
    $.fn.zhpSelect = function (options) {
        var index=999+this.length;           //修正后续的会被遮挡
        this.each(function () {
            var $obj = $(this);
            if($obj.data('toggle')!='selectpicker') {
            Do.ready('chosen', function () {
                $search = $obj.attr('search') == 'true' ? false : true;
                options = $.extend({
                    lang: zhpConfig.lang,
                    disable_search: $search,
                    search_contains: true,
                    inherit_select_classes: true
                }, options);
                //修正一下显示的尺寸
                if ($obj.attr('style')) {
                    options.style = $obj.attr('style');
                } else if ($obj.attr('width')) {
                    var w = $obj.attr('width');
                    w += w.indexOf('px') > 0 ? '' : 'px';
                    options.style += ";width:" + w;
                }
                //console.log(options);
                var result = $obj.chosen(options);
                if($obj.hasClass('form-control')){
                    var cobj = result.next();
                    var ccobj = cobj.find('.chosen-drop').first();
                    ccobj.css({'margin-left':'-1px', 'width':cobj.outerWidth()});
                    cobj.css('z-index',index--);
                }
            });
            }
        });
    };

    //时间插件
    $.fn.zhpTime = function (options) {
        var defaults = {
            yearStart: 1900,
            yearEnd: 2050,
            format:	'Y-m-d H:i:00',
            formatTime:	'H:i',
            formatDate:	'Y-m-d',
            scrollInput: false, //屏蔽输入框中的鼠标滚动事件触发的日期变更!原因是datepicker组件未对此操作的日期范围进行判断！
            step: 10
        };
        options = $.extend(defaults, options);
        this.each(function () {
            var id = this;
            Do.ready('time', function () {
                $.datetimepicker.setLocale($.zui.clientLang());
                $(id).datetimepicker(options);
            });
        });
    };

    //日期插件
    $.fn.zhpDate = function (options) {
        var defaults = {
            yearStart: 1900,
            yearEnd: 2050,
            format: 'Y-m-d',
            formatDate: 'Y-m-d',
            timepicker: false,
            scrollInput: false, //屏蔽输入框中的鼠标滚动事件触发的日期变更!原因是datepicker组件未对此操作的日期范围进行判断！
        }
        options = $.extend(defaults, options);
        this.each(function () {
            var $obj = $(this);
            Do.ready('time', function () {
                $.datetimepicker.setLocale($.zui.clientLang());
                $val = $obj.val();
                $p = $obj.parent();
                $id = $obj.attr('id');
                if (!$id) {
                    $id = 'datetime_' + $.zui.uuid();
                    $obj.attr('id', $id);
                }
                if (!$p.hasClass('input-group')) {
                    $html = $('<div class="input-group"></div>');
                    $idc = $obj.clone();
                    $html.append($idc);
                    $obj.after($html);
                    $obj.remove();
                    $obj = $idc;
                }
                if($obj.attr('title')){
                    $obj.before($('<span>').addClass('input-group-addon').html($obj.attr('title')));
                }
                if ($obj.attr('max-date')) {
                    options.onShow = function () {
                        var mid = $obj.attr('max-date');
                        var p = $obj.parent().parent().parent().find('input');
                        var lists = [];
                        $.each(p, function (k, v) {
                            lists.push(v);
                        });
                        //检测是否为日期
                        var midval = false;
                        var ereg = /^(\d{1,4})(-|\/)(\d{1,2})(-|\/)(\d{1,2})$/;
                        if (mid.match(ereg)) {
                            midval = mid;
                        } else {
                            if (mid === '.next') {
                                var i = lists.indexOf($obj[0]);
                                i++;
                                mid = $(lists[i]);
                            } else if (mid === '.prev') {
                                var i = lists.indexOf($obj[0]);
                                i--;
                                mid = $(lists[i]);
                            } else {
                                mid = $('#' + mid);
                            }
                            midval = mid.val() ? mid.val() : false
                        }
                        this.setOptions({
                            maxDate: midval
                        })
                    };
                }
                if ($obj.attr('min-date')) {
                    options.onShow = function () {
                        var mid = $obj.attr('min-date');
                        var p = $obj.parent().parent().parent().find('input');
                        var lists = [];
                        $.each(p, function (k, v) {
                            lists.push(v);
                        })
                        //检测是否为日期
                        var midval = false;
                        var ereg = /^(\d{1,4})(-|\/)(\d{1,2})(-|\/)(\d{1,2})$/;
                        if (mid.match(ereg)) {
                            midval = mid;
                        } else {
                            if (mid === '.next') {
                                var i = lists.indexOf($obj[0]);
                                i++;
                                mid = $(lists[i]);
                            } else if (mid === '.prev') {
                                var i = lists.indexOf($obj[0]);
                                i--;
                                mid = $(lists[i]);
                            } else {
                                mid = $('#' + mid);
                            }
                            midval = mid.val() ? mid.val() : false
                        }
                        this.setOptions({
                            minDate: midval
                        })
                    };
                }
                $obj.attr('type', 'text');
                $obj.removeClass('js-date').addClass('form-control');
                $obj.attr('readonly', true);
                //清除按钮
                $group1 = $('<span class="input-group-addon rightborder"><span class="icon icon-times"></span></span>').css({cursor: 'pointer'}).click(function () {
                    $obj.val('')
                });
                //日期选择按钮
                $group2 = $('<span class="input-group-addon rightborder"><span class="icon icon-calendar"></span></span>').css({cursor: 'pointer'}).click(function () {
                    $obj.datetimepicker('show')
                });
                $obj.after($group1).after($group2);
                $obj.datetimepicker(options);
            });
        });
    };

    //上传文件
    $.fn.zhpFileUpload = function (options) {
        var uuuu = new Array();
        this.each(function () {
            var $name = $(this).attr('name');
            var upButton = $('<div>').attr('data', $name).attr('id', "uploader_" + $name).addClass('webuploader');

            //加载HTML标签中的设置
            $.each(this.attributes, function () {
                if (this.name.indexOf("data-") == 0) {
                    if (this.value == 'true')
                        this.value = true;
                    if (this.value == 'false')
                        this.value = false;
                    upButton.attr(this.name, this.value);
                    $(this).removeAttr(this.name);
                }
            });

            var multi = $(this).attr('multi') == 'true';
            var auto = $(this).attr('auto') == 'true';
            var max = $(this).attr('maxnum');
            var start = $(this).attr('start');
            var preview = $(this).attr('preview');
            if (!preview)
                preview = $.zui.uuid();
            //var cut = $(this).attr('data-cut') == 'true' && !multi;
            if (multi && $('#displayorder').attr('id') != 'displayorder') {
                var $do = $('<input type="hidden" id="displayorder" name="displayorder">');
                $(this).after($do);
            }
            $(this).after(upButton);
            $(this).remove();

            var opts = {};
            opts.type = 'jpg,png,bmp,jpeg';
            opts.multi = multi;
            opts.auto = auto;
            if (max)
                opts.maxnum = max;
            opts.preview = preview;
            if (start)
                opts.idSuffix = start;
            if (multi) {
                upButton.zhpMultiUpload(opts);
            } else {
                uuuu.push({'id': 'uploader_' + $name, 'preview': preview});
            }
        });
        $.each(uuuu, function (ii, v) {
            $('#' + v.id).zhpImgUpload({type: 'jpg,png,bmp,jpeg', preview: v.preview});
        });
    };

    //多图上传，同一页面只允许有一个批量上传控件
    $.fn.zhpMultiUpload = function (options) {
        var defaults = {
            paste: document.body,
            //dnd: '#uploader .queueList',
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/*'
            },
            formData: {
            },
            xcompress: {
                width: 800,
                height: 800,
                // 图片质量，只有type为`image/jpeg`的时候才有效。
                quality: 90,
                // 是否允许放大，如果想要生成小图的时候不失真，此选项应该设置为false.
                allowMagnify: false,
                // 是否允许裁剪。
                crop: false,
                // 是否保留头部meta信息。
                preserveHeaders: true,
                // 如果发现压缩后文件大小比原来还大，则使用原来图片
                // 此属性可能会影响图片自动纠正功能
                noCompressIfLarger: false,
                // 单位字节，如果图片大小小于此值，不会采用压缩。
                compressSize: 0
            },
            disableGlobalDnd: false,
            chunked: true,
            fileNumLimit: options.maxnum ? options.maxnum : false, //TODO 文件总数，应该再有一个关联项来记录已经上传的个数
            //fileSizeLimit: 6 * 1024 * 1024, //上传总尺寸 10M
            //fileSingleSizeLimit: 1 * 1024 * 1024, //单个文件尺寸 1M
            deleteUrl: zhpConfig.deleteUrl,
            uploadUrl: zhpConfig.uploadUrl,
            sortable: true,
            hasdesc: false
        }
        if (options.type)
            defaults.accept.extensions = options.type;
        var options = $.extend(defaults, options);
        this.each(function () {
            var upButton = $(this);
            var $dataname = $(this).attr('data');

            //加载HTML标签中的设置
            upButton.append($('<div id="filePicker"></div>'));
            options = $.extend(options, upButton.data());
            options.formData = $.extend({'file_name': $(this).attr('name')}, upButton.data());

            var uploaderId = $(this).attr('id');
            if (!uploaderId) {
                uploaderId = $.zui.uuid();
            }

            var $previewArea = options.preview ? options.preview : upButton.attr('preview');

            var $queue = $('<ul class="filelist grid"></ul>');

            // 图片容器
            if (!$previewArea) {
                $previewArea = uploaderId + '_preview';
            }
            var $preview = $('#' + $previewArea);
            if (!$preview.attr('id')) {
                $preview = $('<div id="' + $previewArea + '"></div>').appendTo(upButton);
            } else {
                $preview.addClass('webuploader');
            }
            $preview.addClass('preview');
            if (!$preview.find('ul').length) {
                $queue.appendTo($preview);
            } else {
                var $queue = $preview.find('ul').addClass('filelist grid');
            }
            $queue.css('width', upButton.width());
            // 状态栏，包括进度和控制按钮
            var $statusBar = $('<div class="statusBar" style="display:none;"></div>')
                    .appendTo(upButton),
                    // 总体进度条
                    $progress = $('<div class="progress"><div class="progress-bar"></div></div>').appendTo($statusBar).hide(),
                    // 文件总体选择信息。
                    $info = $('<div class="info"></div>').appendTo($statusBar),
                    // 添加的文件数量
                    fileCount = 0,
                    // 添加的文件总大小
                    fileSize = 0,
                    // 优化retina, 在retina下这个值是2
                    ratio = window.devicePixelRatio || 1,
                    // 缩略图大小
                    thumbnailWidth = 300 * ratio,
                    thumbnailHeight = 180 * ratio,
                    // 可能有pedding, ready, uploading, confirm, done.
                    state = 'ready',
                    // 所有文件的进度信息，key为file id
                    percentages = {};

            var $btnsId = uploaderId + '_btns';
            var $btns = $('<div>').attr('id', $btnsId).css('float', 'left');
            var $uploadBtn = $('<div>').addClass('webuploader-pick').css({'float': 'left', 'margin-left': '2px'}).html(zhpLang('Upload'));
            upButton.append($btns).append($uploadBtn);

            var $data = $('#' + $dataname + '_list');
            if (!$data.length)
                var $data = $('<div style="display:none;"></div>').attr('id', $dataname + '_list').appendTo(upButton);
            else {
                $data.find('input').each(function (index, e) {
                    $li = $(e);
                    $li.attr('id', uploaderId + (++index));
                });
            }

            /*创建上传*/
            Do.ready('webuploader', 'tips', 'sortable', function () {
                //console.log('multi,' + uploaderId);
                window[uploaderId] = WebUploader.create($.extend({
                    swf: zhpConfig.libDir + 'webuploader/Uploader.swf',
                    server: options.uploadUrl,
                    pick: {
                        id: '#filePicker',
                        label: options.text ? options.text : zhpLang('Select pictures'),
                        multiple: true
                    },
                    resize: false,
                    auto: false,
                    cutData: []
                }, options));
                // 添加“添加文件”的按钮，
                window[uploaderId].addButton({
                    id: '#' + $btnsId,
                    label: options.text ? options.text : zhpLang('Select pictures'),
                    style: 'webuploader-pick'
                });
                /**
                 * 将文件添加到队列前的操作
                 * @param {type} file
                 * @returns {undefined}
                 */
                window[uploaderId].onBeforeFileQueued = function (file) {
                };

                /**
                 * 添加文件到上传队列
                 * @param {type} file
                 * @returns {uploaderSingle_L34}
                 */
                window[uploaderId].onFileQueued = function (file) {
                    fileCount++;
                    fileSize += file.size;
                    if (fileCount === 1) {
                        $statusBar.show();
                    }
                    //创建view
                    $btns.show();
                    $uploadBtn.removeClass('disabled');
                    $('#filePicker').hide();
                    var order = file.id.replace('WU_FILE_', '');
                    var hd = '';
                    if (window[uploaderId].options.hasdesc) {
                        hd = '<p class="imgDesc"><textarea name="file_desc[' + order + ']" class="form-control large"></textarea></p>';
                    }
                    var $li = $('<li class="" id="' + file.id + '" data-order="' + order + '">' +
                            '<p class="imgWrap"></p>' + hd +
                            '</li>');
                    var $cbtns = getBtns(file);
                    $li.append($cbtns);
                    var $wrap = $li.find('p.imgWrap'),
                            $info = $('<p class="error"></p>'),
                            showError = function (code) {
                                switch (code) {
                                    case 'exceed_size':
                                        text = '文件大小超出';
                                        break;
                                    case 'interrupt':
                                        text = '上传暂停';
                                        break;
                                    default:
                                        text = '上传失败，请重试';
                                        break;
                                }
                                $info.text(text).appendTo($li);
                            }
                    if (file.getStatus() === 'invalid') {
                        showError(file.statusText);
                    } else {
                        // @todo 图片裁剪，点击显示大图
                        $wrap.text('预览中');
                        window[uploaderId].makeThumb(file, function (error, src) {
                            if (error) {
                                $wrap.text('不能预览');
                                return;
                            }
                            var img = $('<img src="' + src + '">');
                            $wrap.empty().append(img);
                        }, thumbnailWidth, thumbnailHeight);
                        percentages[ file.id ] = [file.size, 0];
                        file.rotation = 0;
                    }
                    file.on('statuschange', function (cur, prev) {
                        // 成功
                        if (cur === 'error' || cur === 'invalid') {
                            showError(file.statusText);
                            percentages[ file.id ][ 1 ] = 1;
                        } else if (cur === 'interrupt') {
                            showError('interrupt');
                        } else if (cur === 'queued') {
                            percentages[ file.id ][ 1 ] = 0;
                        } else if (cur === 'progress') {
                            $info.remove();
                        } else if (cur === 'complete') {
                            $li.append('<span class="success"></span>');
                        }
                        $li.removeClass('state-' + prev).addClass('state-' + cur);
                    });

                    $li.on('mouseenter', function () {
                        $cbtns.stop().animate({height: 30});
                    });

                    $li.on('mouseleave', function () {
                        $cbtns.stop().animate({height: 0});
                    });

                    $li.appendTo($queue);
                    sortFile();
                    //$title = $('<p class="title">this is a cover</p>');
                    //$('.filelist p.title').remove();
                    //$('.filelist').children().first().append($title);
                    //view 创建完成
                    setState('ready');
                    updateTotalProgress();
                };

                /**
                 * 从队列中删除文件
                 * @param {type} file
                 * @returns {uploaderSingle_L34}
                 */
                window[uploaderId].onFileDequeued = function (file) {
                    fileCount--;
                    fileSize -= file.size;
                    if (!fileCount) {
                        setState('pedding');
                    }
                    //销毁View
                    var $li = $('#' + file.id);
                    delete percentages[ file.id ];
                    updateTotalProgress();
                    $li.off().find('.file-panel').off().end().remove();

                    updateTotalProgress();
                };

                /**
                 * 开始上传
                 * @param {type} file
                 * @returns {undefined}
                 */
                window[uploaderId].onUploadStart = function (file) {
                    //var formData = $.extend({'uploadtype': options.uploadtype, 'ajax': 1, 'cutdata': this.cutData}, obj);
                    var formData = {'uploadtype': options.uploadtype, 'ajax': 1, 'cutdata': this.cutData};
                    formData = $.extend(options.formData, formData);
                    window[uploaderId].option('formData', formData);
                    upButton.attr('disabled', true);
                    upButton.find('.webuploader-pick span').text(' 等待');
                };

                /**
                 * 处理进度条
                 * @param {type} file
                 * @param {type} percentage
                 * @returns {undefined}
                 */
                window[uploaderId].onUploadProgress = function (file, percentage) {
                    var $li = $('#' + file.id),
                            $percent = $li.find('.progress span');

                    $percent.css('width', percentage * 100 + '%');
                    percentages[ file.id ][ 1 ] = percentage;
                    updateTotalProgress();
                };

                /**
                 * 上传完成
                 * @param {type} file
                 * @param {type} result
                 * @returns {undefined}
                 */
                window[uploaderId].onUploadSuccess = function (file, result) {
                    if (result.status == 0) {
                        toastr.error(result.info);
                        window[uploaderId].cancelFile(file);
                        window[uploaderId].stop(true);
                    } else {
                        //TODO 上传的结果需要实时展现，并支持删除，下一版实现
                        var id = uploaderId + file.id.replace('WU_FILE_', '');
                        $data.append("<input type='hidden' id='" + id + "' name='" + $dataname + "[" + file.id.replace('WU_FILE_', '') + "]'  value='" + result.file.filepath + "' />");
                    }
                };

                /**
                 * 上传出错
                 * @param {type} param1
                 * @param {type} param2
                 */
                window[uploaderId].onError = function (code) {
                    var msg = code;
                    switch (code) {
                        case 'Q_TYPE_DENIED':
                            msg = '对不起，你选择了系统不支持的图片类型！';
                            break;
                        case 'Q_EXCEED_NUM_LIMIT':
                            msg = '你选择了太多的文件了！最多只能选择' + window[uploaderId].options.maxnum + '个文件！';
                            break;
                        case 'F_EXCEED_SIZE':
                            msg = '文件太大了，你只能提交不大于' + window[uploaderId].options.fileSingleSizeLimit + '字节的文件！';
                            break;
                        case 'F_DUPLICATE':
                            msg = '这个文件已经选择了，请选择其它文件！';
                            break;
                        case 'Q_EXCEED_SIZE_LIMIT':
                            msg = '你选择的这些文件超出了最大限额，你本次总上传空间为' + window[uploaderId].options.fileSizeLimit + '字节！';
                            break;
                    }
                    zalert(msg, 'error');
                };

                /**
                 * 上传出错
                 * @param {type} param1
                 * @param {type} param2
                 */
                window[uploaderId].onUploadError = function (file) {
                    zalert('文件上传失败', 'error');
                };

                /**
                 * 其它操作处理
                 * @param {type} param1
                 * @param {type} param2
                 * @param {type} param3
                 */
                window[uploaderId].on('all', function (type) {
                    switch (type) {
                        case 'uploadFinished':
                            setState('confirm');
                            break;
                        case 'startUpload':
                            setState('uploading');
                            break;

                        case 'stopUpload':
                            setState('paused');
                            break;

                    }
                });

                $queue.find('li').each(function (index, e) {
                    var $li = $(e);
                    var id = 'WU_FILE_' + (++index);
                    //这里显示的是以前上传的文件，直接给上传文件个数扣除
                    if (window[uploaderId].options.fileNumLimit != false) {
                        window[uploaderId].options.fileNumLimit--;
                        if (window[uploaderId].options.fileNumLimit == 0)
                            window[uploaderId].options.fileNumLimit = -1;
                    }
                    var $cbtns = getBtns(id);
                    $li.append($cbtns).addClass('state-complete').attr('id', id).attr('data-order', index);
                    $li.on('mouseenter', function () {
                        $cbtns.stop().animate({height: 30});
                    });

                    $li.on('mouseleave', function () {
                        $cbtns.stop().animate({height: 0});
                    });
                });

                function getBtns(file) {
                    if (typeof (file) == 'string') {
                        var $id = file.replace('WU_FILE_', '');
                    } else {
                        var $id = file.id.replace('WU_FILE_', '');
                    }
                    var $cbtns = $('<div class="file-panel" data-id="' + $id + '">' +
                            '<span class="cancel">' + zhpLang('Delete') + '</span></div>');
                    $cbtns.on('click', function () {
                        if ($cbtns.parent().hasClass("state-complete") || typeof (file) == 'string') {
                            if (!window[uploaderId].options.deleteUrl)
                                return;
                            var $id = $(this).attr('data-id');
                            var $vid = $('#' + uploaderId + $id);
                            $path = $vid.val();
                            if (!$path) {
                                zalert('奇怪，我好像没发现你要删除什么东西？');
                                return false;
                            }
                            queryData = $.extend({path:$path, 'ajax': 1}, window[uploaderId].options.formData);
                            $.ajax({
                                type: 'get',
                                url: window[uploaderId].options.deleteUrl,
                                data: queryData,
                                cache: false,
                                dataType: 'json',
                                success: function (result) {
                                    if (result.status == 0) {
                                        zalert(result.info, 'error');
                                        return;
                                    } else {
                                        if (window[uploaderId].options.fileNumLimit < 1)
                                            window[uploaderId].options.fileNumLimit = 0;
                                        window[uploaderId].options.fileNumLimit++;
                                        if (window[uploaderId].options.fileNumLimit > window[uploaderId].options.maxnum)
                                            window[uploaderId].options.fileNumLimit = window[uploaderId].options.maxnum;
                                        if (typeof (file) == 'string')
                                            $('#' + file).remove();
                                        else
                                            window[uploaderId].removeFile(file);
                                        $vid.remove();
                                    }
                                },
                                error: function (result) {
                                    if (result.readyState) {
                                        var result = $.parseJSON(result.responseText);
                                    }
                                    var msg = result.info;
                                    if (!msg)
                                        msg = '未知错误！';
                                    zalert(msg, 'error');
                                    //console.log('error');
                                    //console.log(result);
                                    return;
                                }
                            });
                        } else {
                            window[uploaderId].removeFile(file);
                        }
                    });
                    return $cbtns;
                }

                function sortFile() {
                    if (window[uploaderId].options.sortable)
                        $('.filelist').sortable({
                            selector: 'li',
                            initstart: function (e) {
                                if (window[uploaderId].options.hasdesc) {
                                    e.element.find('textarea').focus();
                                }
                            },
                            start: function () {
                                //$('.filelist p.title').remove();
                                $('.filelist li.invisible').append($('<span class="hints">Drag to here</span>'));
                            },
                            finish: function (e) {
                                $('#displayorder').val($('.filelist').data('zui.sortable').orders.toString());
                                $('.filelist span.hints').remove();
                                if (window[uploaderId].options.hasdesc) {
                                    e.element.find('textarea').focus();
                                }
                                //var $title = $('<p class="title">this is a cover</p>');
                                //$('.filelist').children().first().append($title);
                            }
                        });
                }

                sortFile();

                //更新总进度条
                function updateTotalProgress() {
                    var loaded = 0,
                            total = 0,
                            spans = $progress.children(),
                            percent;
                    $.each(percentages, function (k, v) {
                        total += v[ 0 ];
                        loaded += v[ 0 ] * v[ 1 ];
                    });
                    percent = total ? loaded / total : 0;
                    spans.text(Math.round(percent * 100) + '%');
                    spans.css('width', Math.round(percent * 100) + '%');
                    updateStatus();
                }
                //处理提示信息
                function updateStatus() {
                    var text = '', stats;
                    if (state === 'ready') {
                        text = '选中' + fileCount + '张图片，共' +
                                WebUploader.formatSize(fileSize) + '。';
                    } else if (state === 'confirm') {
                        stats = window[uploaderId].getStats();
                        if (stats.uploadFailNum) {
                            text = '已成功上传' + stats.successNum + '张图片，' +
                                    stats.uploadFailNum + '张图片上传失败，<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'
                        }
                    } else {
                        stats = window[uploaderId].getStats();
                        text = '共' + fileCount + '张（' +
                                WebUploader.formatSize(fileSize) +
                                '），已上传' + stats.successNum + '张';
                        if (stats.uploadFailNum) {
                            text += '，失败' + stats.uploadFailNum + '张';
                        }
                    }
                    $info.html(text);
                }

                //状态监控
                function setState(val) {
                    var file, stats;
                    if (val === state) {
                        return;
                    }
                    $uploadBtn.removeClass('state-' + state);
                    $uploadBtn.addClass('state-' + val);
                    state = val;
                    switch (state) {
                        case 'pedding':
                            //$queue.hide();
                            $uploadBtn.hide();
                            $statusBar.addClass('element-invisible');
                            window[uploaderId].refresh();
                            break;
                        case 'ready':
                            $('#' + $btnsId).removeClass('element-invisible');
                            //$queue.show();
                            $uploadBtn.show();
                            $statusBar.removeClass('element-invisible');
                            window[uploaderId].refresh();
                            break;
                        case 'uploading':
                            $('#' + $btnsId).addClass('element-invisible');
                            $progress.show();
                            $uploadBtn.text('暂停上传');
                            break;
                        case 'paused':
                            $progress.show();
                            $uploadBtn.text('继续上传');
                            break;
                        case 'confirm':
                            $progress.hide();
                            $uploadBtn.text(zhpLang('Upload')).addClass('disabled');
                            stats = window[uploaderId].getStats();
                            if (stats.successNum && !stats.uploadFailNum) {
                                setState('finish');
                                return;
                            }
                            break;
                        case 'finish':
                            $('#' + $btnsId).removeClass('element-invisible');
                            stats = window[uploaderId].getStats();
                            if (stats.successNum) {
                                toastr.info('文件已经成功上传，编辑完信息后请点击“提交”...');
                            } else {
                                // 没有成功的图片，重设
                                state = 'done';
                                location.reload();
                            }
                            break;
                    }
                    updateStatus();
                }

                $uploadBtn.on('click', function () {
                    if ($(this).hasClass('disabled')) {
                        return false;
                    }
                    if (state === 'ready') {
                        window[uploaderId].upload();
                    } else if (state === 'paused') {
                        window[uploaderId].upload();
                    } else if (state === 'uploading') {
                        window[uploaderId].stop();
                    }
                });

                //批量上传时的排序
                fileSort = function (list1, list2) {
                    var order = $('.filelist').data('zui.sortable').orders;
                    var id1 = list1.id.replace('WU_FILE_', '');
                    var id2 = list2.id.replace('WU_FILE_', '');
                    var id1 = $('#' + list1.id).attr('data-order');
                    var id2 = $('#' + list2.id).attr('data-order');
                    return id1 - id2;
                };

                $info.on('click', '.retry', function () {
                    window[uploaderId].retry();
                });

                $info.on('click', '.ignore', function () {
                    zalert('oops!');
                });
                updateTotalProgress();
                $('#filePicker').hide();
                setState('pedding');
                //console.log(state);
            });
        });
    };

    //上传图片
    $.fn.zhpImgUpload = function (options) {
        var defaults = {
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/*'
            },
            formData: {
            },
            xcompress: {
                width: 8000,
                height: 8000,
                // 图片质量，只有type为`image/jpeg`的时候才有效。
                quality: 90,
                // 是否允许放大，如果想要生成小图的时候不失真，此选项应该设置为false.
                allowMagnify: false,
                // 是否允许裁剪。
                crop: true,
                // 是否保留头部meta信息。
                preserveHeaders: true,
                // 如果发现压缩后文件大小比原来还大，则使用原来图片
                // 此属性可能会影响图片自动纠正功能
                noCompressIfLarger: false,
                // 单位字节，如果图片大小小于此值，不会采用压缩。
                compressSize: 0
            },
            disableGlobalDnd: false,
            chunked: true,
            deleteUrl: zhpConfig.deleteUrl,
            uploadUrl: zhpConfig.uploadUrl,
            sortable: false,
            hasdesc: false,
            uploadtype: 0,
            type: '',
            cut: false,
            cutratio: 1,
            cutwidth: 300,
            cutheight: 300,
            value: ''
        };
        if (options.type)
            defaults.accept.extensions = options.type;
        options = $.extend(defaults, options);
        this.each(function () {
            var upButton = $(this);
            //加载HTML标签中的设置
            options = $.extend(options, upButton.data());
            options.formData = $.extend({'file_name': $(this).attr('name')}, upButton.data());

            var uploaderId = $(this).attr('id');
            if (!uploaderId) {
                uploaderId = $.zui.uuid();
            }

            var $previewArea = options.preview ? options.preview : upButton.attr('preview');
            // 图片容器
            if (!$previewArea) {
                $previewArea = uploaderId + '_preview';
            }
            var $preview = $('#' + $previewArea);
            if (!$preview.attr('id')) {
                var sss = '';
                if (options.src)
                    sss = ' src="' + options.src + '"';
                $preview = $('<div id="' + $previewArea + '"><img' + sss + '></div>').appendTo(upButton.parent());
            }
            $preview.addClass('preview');
            $preview.addClass('webuploader');
            var urlValId = upButton.attr('data');
            var urlVal = $('#' + urlValId);
            if (!urlVal.length) {
                urlVal = $('<input>').attr('id', urlValId).attr('name', urlValId).attr('type', 'hidden');
                urlVal.val(options.value);
                urlVal.appendTo(upButton.parent());
            }
            if (options.required) {
                urlVal.attr('datatype', '*');
            }

            var $progress = $('<div style="position: absolute; bottom: 0;padding: 5px; display: none;"></div>');
            $progress.append('<div class="progress"><div class="progress-bar"></div></div>');
            $progress.appendTo($preview);
            // 上传按钮
            var $btnsId = uploaderId + '_btns';
            var $btns = $('<div>').attr('id', $btnsId).css('float', 'left');
            var $uploadBtn = $('<div>').addClass('webuploader-pick').css({'float': 'left', 'margin-left': '2px'}).html(zhpLang('Upload'));
            var $selectImg = $('<div>').css({display:'table'}).append($btns).append($uploadBtn).hide();
            //$selectImg.appendTo($preview);
            $selectImg.insertBefore($preview.find('img'))
            /*创建上传*/
            Do.ready('webuploader', 'cropper', function () {
                //console.log('singer,' + uploaderId);
                window[uploaderId] = WebUploader.create($.extend({
                    swf: zhpConfig.libDir + 'webuploader/Uploader.swf',
                    server: options.uploadUrl,
                    pick: {
                        id: upButton,
                        label: options.text ? options.text : zhpLang('Select pictures'),
                        multiple: false
                    },
                    resize: true,
                    auto: false,
                    cutData: []
                }, options));
                // 添加“添加文件”的按钮，
                window[uploaderId].addButton({
                    id: '#' + $btnsId,
                    label: options.text ? options.text : zhpLang('Select pictures'),
                    style: 'webuploader-pick'
                });

                /**
                 * 将文件添加到队列前的操作
                 * @param {type} file
                 * @returns {undefined}
                 */
                window[uploaderId].onBeforeFileQueued = function (file) {
                    $uploadBtn.show();
                    upButton.hide();
                    $selectImg.show();
                    //修复一下按钮的内部控件的尺寸
                    $selectImg.children().first().children().next().width($('#' + $btnsId).width()).height($('#' + $btnsId).height());
                    this.reset();
                };

                /**
                 * 添加文件到上传队列
                 * @param {type} file
                 * @returns {uploaderSingle_L34}
                 */
                window[uploaderId].onFileQueued = function (file) {
                    var $img = $preview.find('img');
                    if (!this.cutReady)
                        this.cutReady = 1;
                    var $this = this;
                    window[uploaderId].makeThumb(file, function (error, src) {
                        if (error) {
                            $preview.replaceWith('<span>不能预览</span>');
                            return;
                        }
                        $img.attr('src', src);
                        //$uploadBtn.css({display: 'block'});
                        $progress.css({width: $img.width()}).show();
                        $.zui.imgReady(src, function () {
                            if (options.cut) {
                                if ($this.cutReady == 1) {
                                    $img.cropper({
                                        strict: true,
                                        aspectRatio: options.cutratio,
                                        autoCrop: true,
                                        background: true,
                                        center: true,
                                        checkImageOrigin: false,
                                        cropBoxMovable: true,
                                        cropBoxResizable: true,
                                        doubleClickToggle: false,
                                        dragCrop: false,
                                        guides: true,
                                        highlight: true,
                                        minCanvasHeight: 0,
                                        minCanvasWidth: 0,
                                        minContainerHeight: 100,
                                        minContainerWidth: 200,
                                        minCropBoxHeight: 0,
                                        minCropBoxWidth: 0,
                                        modal: true,
                                        mouseWheelZoom: true,
                                        movable: true,
                                        preview: ".img-preview",
                                        responsive: false,
                                        rotatable: false,
                                        scalable: false,
                                        strict: true,
                                                touchDragZoom: true,
                                        wheelZoomRatio: 0.1,
                                        zoomable: true,
                                        crop: function (e) {
                                            var json = [
                                                '{"x":' + parseInt(e.x),
                                                '"y":' + parseInt(e.y),
                                                '"oh":' + parseInt(e.currentTarget.naturalHeight),
                                                '"ow":' + parseInt(e.currentTarget.naturalWidth),
                                                '"height":' + parseInt(e.height),
                                                '"width":' + parseInt(e.width),
                                                '"cutheight":' + parseInt(options.cutheight),
                                                '"cutwidth":' + parseInt(options.cutwidth),
                                                '"rotate":' + parseInt(e.rotate?e.rotate:0) + '}'
                                            ].join();
                                            $this.cutData = json;
                                        }
                                    });
                                    $this.cutReady = 2;
                                } else {
                                    $img.cropper('replace', src);
                                    $img.data().cropper.crop();
                                }
                            }
                        });
                    }, 960, 540);

                    file.on('statuschange', function (cur, prev) {
                        if (prev === 'progress') {
                            $progress.width(0).hide();
                            var $percent = $progress.children().children().first();
                            $percent.css('width', 0);
                            $percent.text('0%');
                            $uploadBtn.hide();
                        }
                        // 成功
                        if (cur === 'error' || cur === 'invalid') {
                            zalert(file.statusText, 'error');
                            window[uploaderId].reset();
                            $img.attr('src', '');
                        } else if (cur === 'interrupt') {
                            //zalert('上传暂停');
                        } else if (cur === 'progress') {
                            $uploadBtn.hide();
                            $progress.show();
                        } else if (cur === 'complete') {
                        }
                    });
                };

                /**
                 * 从队列中删除文件
                 * @param {type} file
                 * @returns {uploaderSingle_L34}
                 */
                window[uploaderId].onFileDequeued = function (file) {
                };

                /**
                 * 开始上传
                 * @param {type} file
                 * @returns {undefined}
                 */
                window[uploaderId].onUploadStart = function (file) {
                    var formData = {'ajax': 1, 'cutdata': this.cutData};
                    formData = $.extend(options.formData, formData);
                    window[uploaderId].option('formData', formData);
                    upButton.attr('disabled', true);
                    upButton.find('.webuploader-pick span').text(' 等待');
                };

                /**
                 * 处理进度条
                 * @param {type} file
                 * @param {type} percentage
                 * @returns {undefined}
                 */
                window[uploaderId].onUploadProgress = function (file, percentage) {
                    var $percent = $progress.children().children().first();
                    $percent.css('width', percentage * 100 + '%');
                    $percent.text(Math.round(percentage * 100) + '%');
                };

                /**
                 * 上传完成
                 * @param {type} file
                 * @param {type} result
                 * @returns {undefined}
                 */
                window[uploaderId].onUploadSuccess = function (file, result) {
                    var $this = this;
                    upButton.attr('disabled', false);
                    upButton.find('.webuploader-pick span').text(' 上传');
                    if (result.status) {
                        urlVal.val(result.file.filepath);
                        //TODO 上传完成后的操作
                        //options.complete(result.file);
                        var $img = $preview.find('img');//$('#uploader_avatar_preview img').data()
                        $img.cropper('destroy');
                        $img.attr('src', result.file.url);
                        $this.cutReady = 1;
                    } else {
                        zalert(result.info, 'error');
                    }
                };

                /**
                 * 上传出错
                 * @param {type} param1
                 * @param {type} param2
                 */
                window[uploaderId].onError = function (code) {
                    var msg = code;
                    switch (code) {
                        case 'Q_TYPE_DENIED':
                            msg = '对不起，你选择了系统不支持的图片类型！';
                            break;
                        case 'Q_EXCEED_NUM_LIMIT':
                            msg = '你选择了太多的文件了！最多只能选择' + window[uploaderId].options.maxnum + '个文件！';
                            break;
                        case 'F_EXCEED_SIZE':
                            msg = '文件太大了，你只能提交不大于' + window[uploaderId].options.fileSingleSizeLimit + '字节的文件！';
                            break;
                        case 'F_DUPLICATE':
                            msg = '这个文件已经选择了，请选择其它文件！';
                            break;
                        case 'Q_EXCEED_SIZE_LIMIT':
                            msg = '你选择的这些文件超出了最大限额，你本次总上传空间为' + window[uploaderId].options.fileSizeLimit + '字节！';
                            break;
                    }
                    zalert(msg, 'error');
                };

                /**
                 * 上传出错
                 * @param {type} param1
                 * @param {type} param2
                 */
                window[uploaderId].onUploadError = function (file) {
                    zalert('文件上传失败', 'error');
                };

                $uploadBtn.on('click', function () {
                    if ($(this).hasClass('disabled')) {
                        return false;
                    }
                    window[uploaderId].upload();
                });

            });
        });
    };

    //编辑器调用
    $.fn.zhpEditor = function () {
        this.each(function () {
            var id = this;
            var $type = $(this).attr('data-type');
            if (!$type)
                $type = '4-odt';
            $(this).removeAttr('data-type');
            var idName = $(this).attr('id');
            var editorName = idName + '_editor';
            $(this).parent().css({'overflow-x': 'hidden'});
            var $maxWidth = $(this).parent().width() - 10;
            Do.ready('editor', function () {
                //编辑器
                var editorConfig = {
                    allowFileManager: false,
                    uploadJson: zhpConfig.uploadUrl,
                    filePostName: 'file',
                    filterMode: false,
                    langType: $.zui.clientLang(),
                    afterBlur: function () {
                        this.sync();
                    },
                    afterUpload: function (url, data) {
                        $('#editor_upload_area').append(
                                $('<input>').attr('name', 'editor_uploaded[]').val(data.file.name).attr('type', 'hidden')
                                );
                    },
                    items: [
                        'bold', 'italic', 'underline',
                        'removeformat', '|', 'image'],
                    minWidth: $maxWidth,
                    width: '100%',
                    extraFileUploadParams: {uploadtype: $type, ajax: 1}
                };
                //上传图片的存值区域
                if ($('#editor_upload_area').attr('id') != 'editor_upload_area') {
                    $(id).parent().append($('<div>').css({'display': 'none'}).attr('id', 'editor_upload_area'));
                }
                var str = editorName + ' = KindEditor.create(id, editorConfig);';
                eval(str);
            });

        });
    };

    //图表插件
    $.fn.zhpChart = function (options) {
        var defaults = {
            data: []
        };
        var options = $.extend(defaults, options);
        var chartObj = this;
        Do.ready('chart', function () {
            var ctx = $(chartObj).get(0).getContext("2d");
            var chartOptions = {
                responsive: true,
                maintainAspectRatio: false,
                animation: false,
                multiTooltipTemplate: "<%= value %>",
            };
            var myLineChart = new Chart(ctx).Line(options.data, chartOptions);
        });
    };

    $.fn.zhpUploader = function (options) {

    };

    //表单页面处理
    $.fn.zhpFormPage = function (options) {
        var defaults = {
            uploadUrl: zhpConfig.uploadUrl,
            uploadType: [],
            form: true
        };
        options = $.extend(defaults, options);
        this.each(function () {
            var form = this;
            form = $(form);
            //表单处理
            if (options.form) {
                form.zhpForm(options);
            }
            //文件上传
            if (form.find(".js-file-upload").length > 0) {
                form.find('.js-file-upload').zhpFileUpload();
            }
            //图片上传
            if (form.find(".js-img-upload").length > 0) {
                form.find('.js-img-upload').zhpImgUpload();
            }
            //多图片上传
            if (form.find('input[type="file"]').length > 0) {
                form.find('input[type="file"]').zhpFileUpload();
            }
            if (form.find(".js-multi-upload").length > 0) {
                form.find('.js-multi-upload').zhpMultiUpload();
            }
            //编辑器
            if (form.find(".js-editor").length > 0) {
                form.find('.js-editor').zhpEditor();
            }
            //时间选择
            if (form.find(".js-time").length > 0) {
                form.find('.js-time').zhpTime();
            }
            //日期选择
            if (form.find(".js-date").length > 0) {
                form.find('.js-date').zhpDate();
            }
            if (form.find('input[type="date"]').length > 0) {
                form.find('input[type="date"]').zhpDate();
            }
            //选择框
            if (form.find("select").length > 0) {
                form.find('select').zhpSelect();
            }
            //验证
            if(form.find('input').length>0){
                form.find('input').each(function(a,b){
                    if($(b).data('required')) {
                        $(b).addClass('required');
                        $(b).attr('datatype', $(b).data('required'));
                    }
                });
            }
        });
    };
})(jQuery);
function zalert(msg, type) {
    if (!type)
        type = 'info';
    Do.ready('base', function () {
        $.zui.alertmsg(type, msg);
    });
}

//表示全局唯一标识符 (GUID)。
$.zui.Guid = function(g) {
    var arr = new Array(); //存放32位数值的数组
    if (typeof (g) == "string") { //如果构造函数的参数为字符串
        InitByString(arr, g);
    } else {
        InitByOther(arr);
    }
    //返回一个值，该值指示 Guid 的两个实例是否表示同一个值。
    this.Equals = function (o) {
        if (o && o.IsGuid) {
            return this.ToString() == o.ToString();
        } else {
            return false;
        }
    };
    //Guid对象的标记
    this.IsGuid = function () {
    };
    //返回 Guid 类的此实例值的 String 表示形式。
    this.ToString = function (format) {
        if (typeof (format) == "string") {
            if (format == "N" || format == "D" || format == "B" || format == "P") {
                return ToStringWithFormat(arr, format);
            } else {
                return ToStringWithFormat(arr, "D");
            }
        } else {
            return ToStringWithFormat(arr, "N");
        }
    };
    //由字符串加载
    function InitByString(arr, g) {
        g = g.replace(/\{|\(|\)|\}|-/g, "");
        g = g.toLowerCase();
        if (g.length != 32 || g.search(/[^0-9,a-f]/i) != -1) {
            InitByOther(arr);
        } else {
            for (var i = 0; i < g.length; i++) {
                arr.push(g[i]);
            }
        }
    }
    //由其他类型加载
    function InitByOther(arr) {
        var i = 32;
        while (i--) {
            arr.push("0");
        }
    }
    /*
     根据所提供的格式说明符，返回此 Guid 实例值的 String 表示形式。
     N  32 位： xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
     D  由连字符分隔的 32 位数字 xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
     B  括在大括号中、由连字符分隔的 32 位数字：{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
     P  括在圆括号中、由连字符分隔的 32 位数字：(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
     */
    function ToStringWithFormat(arr, format) {
        switch (format) {
            case "N":
                return arr.toString().replace(/,/g, "");
            case "D":
                var str = arr.slice(0, 8) + "-" + arr.slice(8, 12) + "-" + arr.slice(12, 16) + "-" + arr.slice(16, 20) + "-" + arr.slice(20, 32);
                str = str.replace(/,/g, "");
                return str;
            case "B":
                var str = ToStringWithFormat(arr, "D");
                str = "{" + str + "}";
                return str;
            case "P":
                var str = ToStringWithFormat(arr, "D");
                str = "(" + str + ")";
                return str;
            default:
                return new Guid();
        }
    }
};

//Guid 类的默认实例，其值保证均为零。
$.zui.Guid.Empty = new $.zui.Guid();
//初始化 Guid 类的一个新实例。
$.zui.Guid.NewGuids = function() {
    var g = "";
    var i = 32;
    while (i--) {
        g += Math.floor(Math.random() * 16.0).toString(16);
    }
    return new $.zui.Guid(g);
};
